package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @Author wzy
 * @Date 2024/2/8 15:56
 * @description: 分布式锁实现
 */
public class SimpleRedisLock implements ILock{
    private String name;//锁名称
    private static final String KEY_PREFIX = "lock:";//统一锁前缀
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";//同一jvm下指定的统一锁的value值前缀
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;//lua脚本
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();//初始化
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));//注入脚本在位置
        UNLOCK_SCRIPT.setResultType(Long.class);//返回值类型
    }
    private StringRedisTemplate stringRedisTemplate;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 尝试获取锁 SET  lock thread1 NX EX 10
     * @param timeoutSec 锁持有时间 过期后自动释放
     * @return
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        //获取线程标识
        String threadId = ID_PREFIX+Thread.currentThread().getId();
        //获取锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX+name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }


    @Override
    public void unLock() {
        //调用lua脚本 将判断锁和释放锁写在lua脚本中 实现代码原子性
        stringRedisTemplate.execute(UNLOCK_SCRIPT,//lua脚本
                Collections.singletonList(KEY_PREFIX+name),//参数 key
                ID_PREFIX+Thread.currentThread().getId()//参数 value
                );
       /* //获取线程标识 不同jvm(服务）前缀不同 同一jvm不同线程的线程id不同
        String threadId = ID_PREFIX+Thread.currentThread().getId();
        //redis中持有锁的线程id
        String threadIdRedis = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        if(threadId.equals(threadIdRedis)){
            //如果当前线程id和redis中持有锁的线程id相同则释放锁
            // 释放锁
            stringRedisTemplate.delete(KEY_PREFIX+name);
        }*/


    }
}
